package com.yanu.trace.t2s.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.yanu.trace.t2s.util.JWTUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@CrossOrigin
public class JwtIntercepter implements HandlerInterceptor {
    //主要功能拦截请求验证token
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }
        String token = request.getHeader("token");
        System.out.println(token);
        if (StringUtils.isEmpty(token)) {
            throw new IllegalArgumentException("token 不能为空");
        }
        if (!JWTUtil.verify(token)) {
            throw new IllegalArgumentException("token 验证失败，请重新登录！");
        }
        RequestContext.set(token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestContext.remove();
    }
}
